﻿using IceDog.RabbitMQ.ConfigurationService.Factories;
using RabbitMQ.Client;
using System;
using System.Text;
using System.Threading;

namespace IceDog.HiBroadcast.Publisher
{
    class Program
    {
        static void Main(string[] args)
        {
            BeforeStart();
            RunMainLoop();
        }
        private static void BeforeStart()
        {
            Console.Clear();
            Console.WriteLine("Server start");
            for (int i = 3; i > 0; i--)
            {
                Console.WriteLine(i);
                Thread.Sleep(1000);
            }
            Console.WriteLine("Server is starting");
        }
        private static void RunMainLoop()
        {
            TextPublish();
        }

        /// <summary>
        /// 文本推送
        /// </summary>
        private static void TextPublish()
        {
            try
            {
                var connectionFactory = FactoryProvider.GetRMQFactory();
                using (var connection = connectionFactory.CreateConnection("hibroadcast.text.publisher.conntection"))
                {
                    //普通频道
                    using (var commonChannel = connection.CreateModel())
                    {
                        //定义交换区名称
                        var exchangeName = "hibroadcast.text.exchange";
                        // 定义绑定key
                        var bindingKey = "hibroadcast.text.routeKey";
                        var routingKey = bindingKey;//这里路由key和绑定的key是一致的
                        // 设置消息属性
                        var properties = commonChannel.CreateBasicProperties();

                        //准备开始推送
                        //发布的消息可以是任何一个(可以被序列化的)字节数组，如序列化对象，一个实体的ID，或只是一个字符串
                        var encoding = new UTF8Encoding();
                        var c = 0;
                        
                        while (true)
                        {
                            Console.WriteLine("输入你想推送的内容");
                            var msg = $"[{++c}]:" + Console.ReadLine();
                            var msgBytes = encoding.GetBytes(msg);
                            commonChannel.BasicPublish(exchange:exchangeName, routingKey: routingKey, basicProperties:properties, body:msgBytes);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("发生了错误：" + ex);
                throw;
            }
        }
    }
}
